﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using System.Configuration;
using System.Data;

namespace ElingOA6_Admin_DSJCJ.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        private BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
        /// <summary>
        /// 系统参数BLL
        /// </summary>
        private BLL.SysParam sysParamBLL = new BLL.SysParam();
        /// <summary>
        /// 登录首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string type="")
        {
            string url = Fetch.Get("url");
            ViewData["url"] = url;
            ViewData["type"] = type;
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult Login()
        {
            bool isSuccess = true;
            string errorMessage = "";
            string loginID = Fetch.Post("txtUserName").Trim();
            if (loginID == "")
            {
                errorMessage = "用户名不能为空！";
                isSuccess = false;
            }
            if (isSuccess)
            {
                string password = Fetch.Post("txtPassword").Trim();

                int result = 0;
                string entityNo = ConfigurationManager.AppSettings["EntityNo"].ToString();
                            
                result = SysLogin(loginID, password, entityNo);
             

                
                if (result == 1)
                {
                    errorMessage = "用户名或密码错误请重新填写！";
                    isSuccess = false;
                }
                else if (result == 2)
                {
                    errorMessage = "你的帐号已经被禁止登陆！";
                    isSuccess = false;
                }
                else if (result == 3)
                {

                    errorMessage = "你的用户名已过期，不能登陆！";
                    isSuccess = false;
                }
                else if (result == 4)
                {
                    errorMessage = "ip受限制,请联系管理员!";
                }
                else if (result == 200)
                {
                    errorMessage = "";
                }
            }
            string url = Fetch.Post("hdUrl");
            string type = Fetch.Post("hdType");
            ViewData["UserName"] = loginID;
            if (errorMessage != "")
            {
                ViewData["url"] = url;
                ViewData["type"] = type;
                ViewData["jsAlert"] = errorMessage;
                return View("index");
            }
            else
            {
                ActionResult actionResult = null;

                BLL.Index adminIndexBLL = new BLL.Index();

                List<Model.PrvFunctList> prvFunctListList = new List<Model.PrvFunctList>();
                if (loginID == "admin")
                {
                    prvFunctListList = adminIndexBLL.GetPrvFunctList();
                }
                else
                {
                    prvFunctListList = adminIndexBLL.GetPrvFunctList(loginID);
                }
                Models.TreeModelList treeModelList = new Models.TreeModelList();
                OperateSession.addList(GlobalConstant.PARAM_PRVFUNCTIONLIST, prvFunctListList);

                if (url == "")
                {
                    if (type == "WSKQ")
                    {

                        BLL.Attendance attendanceBLL = new BLL.Attendance();
                        string str = "";
                        string entityNo = GlobalConstant.ENTITYNO;

                        string userName = OperateSession.get(GlobalConstant.PARAM_USERNAME);
                        bool amAT = false;
                        bool pmAT = false;
                        string minutes = "";
                        string today = DateTime.Now.Date.ToString();
                        string middleTime = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " " + "12:00";
                        //签到显示时间 早上
                        if (DateTime.Parse(middleTime) > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm")))
                        {                       
                            amAT = true;
                        }
                        //签退显示时间 下午
                        if (DateTime.Parse(middleTime) < DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm")))
                        {
                            pmAT = true;
                        }
                        string attendanceFtatus = hrEmplBLL.GetIsAttendance(entityNo, loginID);
                        if (attendanceFtatus == "N")
                        {
                            str = "您不用参加网上考勤或者请联系管理员在后台帮您设置需要考勤";
                        }
                        else
                        {
                            Model.Attendance attendanceModel = new Model.Attendance();
                            attendanceModel = attendanceBLL.GetModel(loginID, today);
                            minutes = sysParamBLL.GetParamValue("OA_Attendance_Minutes", entityNo);
                            DateTime attendanceTime = new DateTime();
                            if (attendanceModel != null)
                            {
                                if (minutes != "")
                                {
                                    attendanceTime = attendanceModel.FAttendanceTime.AddMinutes(double.Parse(minutes));
                                }
                                else
                                {
                                    attendanceTime = attendanceModel.FAttendanceTime;
                                }
                            }
                            else
                            {
                                attendanceTime = DateTime.Now;
                            }
                            if (attendanceTime <= DateTime.Now)
                            {
                                try
                                {
                                    attendanceModel = new Model.Attendance();
                                    attendanceModel.FAttendanceTime = DateTime.Now;
                                    attendanceModel.FAttendanceIP = Common.GenerateUtil.GetClientIPv4Address();
                                    attendanceModel.FDeptNo = hrEmplBLL.GetEmplFromViewByEmplNo(loginID, entityNo).Tables[0].Rows[0]["FDeptNo"].ToString();
                                    attendanceModel.FEmplNo = loginID;
                                    attendanceModel.FEntityNo = entityNo;
                                    attendanceBLL.Add(attendanceModel);
                                    if (amAT)
                                    {
                                        attendanceModel = attendanceBLL.GetModelASC(loginID, today);
                                        str = userName + "，您已经在" + attendanceModel.FAttendanceTime.ToString("HH:mm") + "签到";
                                    }
                                    if (pmAT)
                                    {
                                        attendanceModel = attendanceBLL.GetModel(loginID, today);
                                        str = userName + "，您已经在" + attendanceModel.FAttendanceTime.ToString("HH:mm")
                                            + "签退,如果有误，请在" + attendanceModel.FAttendanceTime.AddMinutes(int.Parse(minutes)).ToString("HH:mm") + "后重新签退";
                                    }
                                }
                                catch (Exception)
                                {
                                    str = "签到失败";
                                }
                            }
                            else
                            {
                                if (amAT)
                                {
                                    attendanceModel = attendanceBLL.GetModelASC(loginID, today);
                                    str = userName + "，您已经在" + attendanceModel.FAttendanceTime.ToString("HH:mm") + "签到,不用重复签到";
                                }
                                if (pmAT)
                                {
                                    attendanceModel = attendanceBLL.GetModel(loginID, today);
                                    str = userName + "，您已经在" + attendanceModel.FAttendanceTime.ToString("HH:mm")
                                        + "签退,请确认签退时间，如果签退有误，请在" + attendanceModel.FAttendanceTime.AddMinutes(int.Parse(minutes)).ToString("HH:mm") + "后重新签退";

                                }
                            }
                        }
                        
                        Response.Write("<script>alert('" + str + "');window.location.href='/';</script>");
                        Response.Flush();
                        Response.End();
                        return null;
                    }
                    else
                    {

                        actionResult = Redirect(Url.Action("Index", "Index"));
                        return actionResult;
                    }
                }
                else
                {
                    Response.Write("<script>window.location.href='" + url + "';</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }
               
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginID"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private int SysLogin(string loginID, string password, string entityNo)
        {
            BLL.PrvUser adminLoginBLL = new BLL.PrvUser();
            Model.PrvUser prvUserModel = adminLoginBLL.GetModelByNameAndPassword(loginID, password, entityNo);
            if (prvUserModel == null) //用户名或密码错误
            {
                return 1;
            }
            else
            {
                if (prvUserModel.FProhibitLogin == 1)
                {
                    return 2;
                }
                else if (prvUserModel.FForeverAvailable != 0)//如果账号不是永久有效，就判断该账号是否已过期
                {
                    DateTime timenow = DateTime.Now.AddDays(-1);
                    if (timenow > prvUserModel.FAvailableDate)//已过期
                    {
                        return 3;
                    }
                }
                OperateSession.add(GlobalConstant.PARAM_LOGINID, prvUserModel.FLogID);//把登陆ID保存到Session
                OperateSession.add(GlobalConstant.PARAM_USERNAME, prvUserModel.FUserName);//登陆用户名称
                OperateSession.add(GlobalConstant.PARAM_SYSYEAR, DateTime.Now.Year.ToString());

                OperateSession.add("EntityNo", prvUserModel.FEntityNo);//公司编码
                OperateSession.add("FEmplNo", prvUserModel.FEmplNo);//员工编号

                //从数据库获取Ntko Office控件序列号
                BLL.Entity entityBll = new BLL.Entity();
                Model.Entity entityModel = entityBll.GetModel(prvUserModel.FEntityNo);
                if (entityModel != null)
                {
                    OperateSession.add(GlobalConstant.PARAM_PRODUCTCAPTION, entityModel.FNTKOCaption);
                    OperateSession.add(GlobalConstant.PARAM_PRODUCTKEY, entityModel.FNTKOKey);
                }


                OperateSession.add(GlobalConstant.PARAM_FEMPLNO, prvUserModel.FEmplNo);

                string loginName = OperateSession.get(GlobalConstant.PARAM_USERNAME);
                //获取部门信息
                string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                if (emplNo != "" && entityNo != "")
                {
                    DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataTable dt = ds.Tables[0];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                            {
                                ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                                ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                                OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                                break;
                            }

                        }
                    }
                }

                prvUserModel.FLastLoginIPAddr = Common.GenerateUtil.GetClientIPv4Address();
                adminLoginBLL.UpdateUserLoginMsg(prvUserModel.FLogID, prvUserModel.FLastLoginIPAddr, prvUserModel.FEmplNo, prvUserModel.FLastLoginIPAddr);
                return 200;
            }

        }
    }
}
